package com.ruanjian.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruanjian.eduservice.entity.EduSubject;
import com.ruanjian.eduservice.entity.excel.subjectData;
import com.ruanjian.eduservice.service.EduSubjectService;
import com.ruanjian.serviceBase.MyException;



public class subjectListen extends AnalysisEventListener<subjectData> {
    private EduSubjectService eduSubjectService;
    public subjectListen(EduSubjectService eduSubjectService) {
        this.eduSubjectService = eduSubjectService;
    }

    public subjectListen() {
    }



    @Override
    public void invoke(subjectData subjectData, AnalysisContext analysisContext) {
        if(subjectData==null)
        {
            throw new MyException(20001,"文件为空");
        }
        EduSubject existOneSubject = this.existOne(subjectData.getOneName());
        if(existOneSubject==null)
        {
            EduSubject eduSubject1 = new EduSubject();
            eduSubject1.setParentId("0");
            eduSubject1.setTitle(subjectData.getOneName());
            eduSubjectService.save(eduSubject1);


        }
        String pid=existOneSubject.getId();
        EduSubject existTwoSubject = this.existTwo(subjectData.getTwoName(), pid);
        if(existTwoSubject==null){
            EduSubject eduSubject2 = new EduSubject();
            eduSubject2.setParentId(pid);
            eduSubject2.setTitle(subjectData.getTwoName());
            eduSubjectService.save(eduSubject2);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }

    //判断一级分类不能重复添加
    private EduSubject existOne(String name)
    {
        QueryWrapper<EduSubject> wrapper=new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id","0");
        EduSubject one = eduSubjectService.getOne(wrapper);

        return one;
    }

    //判断二级分类不能重复添加
    private EduSubject existTwo(String name,String pid)
    {
        QueryWrapper<EduSubject> wrapper=new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id",pid);
        EduSubject two = eduSubjectService.getOne(wrapper);

        return two;
    }
}
